package problem18;

//18.四数之和
//https://leetcode.cn/problems/4sum/

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>>ret = new ArrayList<>();
        int n = nums.length;
        for(int i=0;i<n;) {
            for(int j=i+1;j<n;){
                long _target = (long)target - nums[i] - nums[j];
                System.out.println(_target);
                int left = j+1,right = n-1;
                while(left<right) {
                    long sum = nums[left]+nums[right];
                    if(sum>_target) {
                        right--;
                    }else if(sum<_target) {
                        left++;
                    }else if(sum == _target){
                        System.out.println(_target+" "+sum);
                        List<Integer> tmp = new ArrayList<>();
                        tmp.add(nums[i]);tmp.add(nums[j]);tmp.add(nums[left]);tmp.add(nums[right]);
                        ret.add(tmp);
                        right--;
                        left++;
                        while(left<right && nums[left-1]==nums[left]) {
                            left++;
                        }
                        while(left<right && nums[right+1]==nums[right]) {
                            right--;
                        }
                    }
                }
                j++;
                while(j<n&&nums[j-1]==nums[j]) {
                    j++;
                }
            }
            i++;
            while(i<n&&nums[i-1]==nums[i]){
                i++;
            }
        }
        return ret;
    }
}